<?PHP
  class EventManager {
    private static $handler = null;
  
    /**
     * 
     * @return array;
     */
    public static function GetAllHandler(){
       $res = self::$handler;
       if($res == null){
           if(Cache::contains("eventmanager", "handler")){
               $res = Cache::getData("eventmanager", "handler");
           }
           else{              
               $rows = DataBase::Current()->ReadRows("SELECT * FROM {'dbprefix'}events");
               
               foreach ($rows as $handler) {
		   
		   //testen, ob das Array schon initialisiert wurde.
		   if(!isset($res[$handler->event])){
                     $res[$handler->event] = array();
                   }

                   $res[$handler->event][] = $handler->file;
               }
               
               //print_r($res);
               Cache::setData("eventmanager", "handler", $res);
               self::$handler = $res;
           }
       }
       return $res;
    }
    
    /**
     *
     * @param string $file
     * @param strung $event
     * @return mixed 
     */
    public static function addHandler($file, $event){
       $file  = DataBase::Current()->EscapeString($file);
       $event = DataBase::Current()->EscapeString($event);
       Cache::clear("eventmanager", "handler");
       return DataBase::Current()->Execute("INSERT INTO {'dbprefix'}events (event, file) VALUES ('".$event."','".$file."')");
    }
    
    /**
     *
     * @param string $file
     * @param string $event
     * @return mixed
     */
    public static function removeHandler($file, $event){
       $file  = DataBase::Current()->EscapeString($file);
       $event = DataBase::Current()->EscapeString($event);
       Cache::clear("eventmanager", "handler");
       return DataBase::Current()->Execute("DELETE FROM {'dbprefix'}events WHERE event = '".$event."' AND file = '".$file."'");
    }
    
    /**
     *
     * @param string $name
     * @param array $args 
     */
    public static function RaiseEvent($name,$args){
       $handler = self::getHandler($name);
       if($handler){
         foreach($handler as $file){
           include_once(Settings::getValue("root").$file);
         }
       }
    }
    
    /**
     *
     * @param string $name
     * @return array
     */
    public static function getHandler($name){
       $handler = self::GetAllHandler();
       if(isset($handler[$name]))
       {
            return $handler[$name];
       }
    }
  
  }
?>